<template>
  <div class="feature-importance-comparison">
    <div class="chart-header">
      <h4>
        <Icon type="ios-analytics" size="18" />
        模型特征重要性对比分析
      </h4>
      <div class="chart-controls">
        <Select v-model="selectedCategory" size="small" style="width: 150px;" @on-change="updateChart">
          <Option value="all">全部特征</Option>
          <Option value="historical">历史负荷</Option>
          <Option value="weather">气象特征</Option>
          <Option value="time">时间特征</Option>
        </Select>
        <Select v-model="topN" size="small" style="width: 120px;" @on-change="updateChart">
          <Option value="10">Top 10</Option>
          <Option value="20">Top 20</Option>
          <Option value="30">Top 30</Option>
        </Select>
      </div>
    </div>
    
    <div class="chart-container">
      <div ref="comparisonChart" class="chart-content"></div>
    </div>
    
    <div class="chart-legend">
      <div class="legend-item">
        <span class="legend-color lightgbm"></span>
        <span>LightGBM</span>
      </div>
      <div class="legend-item">
        <span class="legend-color xgboost"></span>
        <span>XGBoost</span>
      </div>
      <div class="legend-item">
        <span class="legend-color ensemble"></span>
        <span>集成权重</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FeatureImportanceComparison',
  props: {
    featureData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedCategory: 'all',
      topN: '20',
      chartInstance: null
    }
  },
  mounted() {
    this.initChart()
  },
  watch: {
    featureData: {
      handler() {
        this.updateChart()
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        this.updateChart()
      })
    },
    
    updateChart() {
      if (!this.featureData || this.featureData.length === 0) {
        return
      }
      
      // 处理数据：按模型分组
      const processedData = this.processFeatureData()
      
      // 渲染图表
      this.renderChart(processedData)
    },
    
    processFeatureData() {
      // 分离不同模型的数据
      const lightgbmData = this.featureData.filter(item => item.model === 'lightgbm')
      const xgboostData = this.featureData.filter(item => item.model === 'xgboost')
      const ensembleData = this.featureData.filter(item => item.model === 'ensemble')
      
      // 获取所有特征名称（去重）
      const allFeatures = new Set()
      lightgbmData.forEach(item => allFeatures.add(item.feat))
      xgboostData.forEach(item => allFeatures.add(item.feat))
      
      // 按类别过滤
      const filteredFeatures = Array.from(allFeatures).filter(feat => {
        if (this.selectedCategory === 'all') return true
        if (this.selectedCategory === 'historical') return feat.startsWith('hist_load_')
        if (this.selectedCategory === 'weather') return feat.startsWith('weather_')
        if (this.selectedCategory === 'time') return feat.startsWith('time_')
        return true
      })
      
      // 构建对比数据
      const comparisonData = filteredFeatures.map(feat => {
        const lgbItem = lightgbmData.find(item => item.feat === feat)
        const xgbItem = xgboostData.find(item => item.feat === feat)
        
        return {
          feature: feat,
          lightgbm: lgbItem ? lgbItem.imp : 0,
          xgboost: xgbItem ? xgbItem.imp : 0,
          total: (lgbItem ? lgbItem.imp : 0) + (xgbItem ? xgbItem.imp : 0)
        }
      })
      
      // 按总重要性排序并取前N个
      comparisonData.sort((a, b) => b.total - a.total)
      return comparisonData.slice(0, parseInt(this.topN))
    },
    
    renderChart(data) {
      const container = this.$refs.comparisonChart
      if (!container || !data.length) return
      
      // 清空容器
      container.innerHTML = ''
      
      const width = container.clientWidth || 800
      const height = Math.max(400, data.length * 25)
      const margin = { top: 20, right: 100, bottom: 40, left: 200 }
      
      // 创建SVG
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
      svg.setAttribute('width', width)
      svg.setAttribute('height', height)
      svg.style.background = 'rgba(7, 19, 50, 0.4)'
      svg.style.borderRadius = '8px'
      
      // 计算比例尺
      const maxValue = Math.max(...data.map(d => Math.max(d.lightgbm, d.xgboost)))
      const xScale = (width - margin.left - margin.right) / maxValue
      const yScale = (height - margin.top - margin.bottom) / data.length
      
      // 绘制背景网格
      for (let i = 0; i <= 5; i++) {
        const x = margin.left + (width - margin.left - margin.right) * i / 5
        const line = document.createElementNS('http://www.w3.org/2000/svg', 'line')
        line.setAttribute('x1', x)
        line.setAttribute('y1', margin.top)
        line.setAttribute('x2', x)
        line.setAttribute('y2', height - margin.bottom)
        line.setAttribute('stroke', 'rgba(255,255,255,0.1)')
        line.setAttribute('stroke-width', '1')
        svg.appendChild(line)
        
        // 添加刻度标签
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
        text.setAttribute('x', x)
        text.setAttribute('y', height - margin.bottom + 15)
        text.setAttribute('text-anchor', 'middle')
        text.setAttribute('fill', '#999')
        text.setAttribute('font-size', '10')
        text.textContent = (maxValue * i / 5).toFixed(1)
        svg.appendChild(text)
      }
      
      // 绘制条形图
      data.forEach((d, i) => {
        const y = margin.top + i * yScale + yScale * 0.1
        const barHeight = yScale * 0.35
        
        // LightGBM条形
        if (d.lightgbm > 0) {
          const rect1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
          rect1.setAttribute('x', margin.left)
          rect1.setAttribute('y', y)
          rect1.setAttribute('width', d.lightgbm * xScale)
          rect1.setAttribute('height', barHeight)
          rect1.setAttribute('fill', '#4ecdc4')
          rect1.setAttribute('opacity', '0.8')
          svg.appendChild(rect1)
          
          // 数值标签
          const text1 = document.createElementNS('http://www.w3.org/2000/svg', 'text')
          text1.setAttribute('x', margin.left + d.lightgbm * xScale + 5)
          text1.setAttribute('y', y + barHeight / 2 + 3)
          text1.setAttribute('fill', '#4ecdc4')
          text1.setAttribute('font-size', '10')
          text1.textContent = d.lightgbm.toFixed(2)
          svg.appendChild(text1)
        }
        
        // XGBoost条形
        if (d.xgboost > 0) {
          const rect2 = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
          rect2.setAttribute('x', margin.left)
          rect2.setAttribute('y', y + barHeight + 2)
          rect2.setAttribute('width', d.xgboost * xScale)
          rect2.setAttribute('height', barHeight)
          rect2.setAttribute('fill', '#ffd93d')
          rect2.setAttribute('opacity', '0.8')
          svg.appendChild(rect2)
          
          // 数值标签
          const text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text')
          text2.setAttribute('x', margin.left + d.xgboost * xScale + 5)
          text2.setAttribute('y', y + barHeight * 1.5 + 5)
          text2.setAttribute('fill', '#ffd93d')
          text2.setAttribute('font-size', '10')
          text2.textContent = d.xgboost.toFixed(2)
          svg.appendChild(text2)
        }
        
        // 特征名称
        const featureText = document.createElementNS('http://www.w3.org/2000/svg', 'text')
        featureText.setAttribute('x', margin.left - 10)
        featureText.setAttribute('y', y + yScale / 2)
        featureText.setAttribute('text-anchor', 'end')
        featureText.setAttribute('fill', '#75deef')
        featureText.setAttribute('font-size', '11')
        featureText.textContent = this.formatFeatureName(d.feature)
        svg.appendChild(featureText)
      })
      
      container.appendChild(svg)
    },
    
    formatFeatureName(feat) {
      // 格式化特征名称
      if (feat.startsWith('hist_load_day')) {
        const match = feat.match(/day(\d+)_t(\d+)/)
        if (match) {
          return `历史负荷 ${match[1]}天前 第${match[2]}点`
        }
      } else if (feat.startsWith('weather_')) {
        const weatherMap = {
          'temp_max': '最高温度',
          'temp_min': '最低温度',
          'precip': '降水量',
          'humidity': '湿度'
        }
        const key = feat.replace('weather_', '')
        return weatherMap[key] || feat
      } else if (feat.startsWith('time_')) {
        const timeMap = {
          'month': '月份',
          'holiday': '节假日',
          'mon': '周一', 'tue': '周二', 'wed': '周三', 'thu': '周四',
          'fri': '周五', 'sat': '周六', 'sun': '周日'
        }
        const key = feat.replace('time_', '')
        return timeMap[key] || feat
      }
      return feat
    }
  }
}
</script>

<style lang="less" scoped>
.feature-importance-comparison {
  background: rgba(7, 19, 50, 0.4);
  border: 1px solid #1a3c58;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h4 {
      color: #75deef;
      font-size: 16px;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .chart-controls {
      display: flex;
      gap: 10px;
    }
  }
  
  .chart-container {
    .chart-content {
      width: 100%;
      min-height: 400px;
      overflow-x: auto;
    }
  }
  
  .chart-legend {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-top: 15px;
    
    .legend-item {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #999;
      font-size: 14px;
      
      .legend-color {
        width: 16px;
        height: 12px;
        border-radius: 2px;
        
        &.lightgbm {
          background: #4ecdc4;
        }
        
        &.xgboost {
          background: #ffd93d;
        }
        
        &.ensemble {
          background: linear-gradient(90deg, #4ecdc4 50%, #ffd93d 50%);
        }
      }
    }
  }
}
</style>